import { shallowRef, reactive, ref, onActivated } from "vue"
import { ElMessageBox, ElNotification } from "element-plus"
import { formatDate } from "/plugins/date"
import { useBasis } from "../basis"
export function useList(modules) {
	const basis = useBasis()
	const loading = shallowRef(true)
	const tableLoading = shallowRef(true)
	const search = reactive(Object.assign({}, modules.search))
	const selection = ref([])
	const tableData = reactive({
		current: 1,
		data: [],
		lastPage: 1,
		size: 10,
		total: 0,
	})
	function reload() {
		if (modules.pagination) {
			if (tableData.current > tableData.lastPage) {
				tableData.current = tableData.lastPage
			}
		}
		modules.getData()
	}
	function toSearch() {
		if (modules.pagination) {
			tableData.current = 1
			tableData.data = []
			tableData.total = 0
			tableData.lastPage = 1
		}
		modules.getData()
	}
	function toRefreshSearch() {
		Object.keys(search).forEach(key => {
			search[key] = ""
		})
		toSearch()
	}
	function onSizeChange(size) {
		tableData.current = 1
		tableData.size = size
		modules.getData()
	}
	function onCurrentChange(current) {
		tableData.current = current
		reload()
	}
	async function toDelete(id) {
		try {
			await postAxios(modules.deleteUrl + "?id=" + id)
			if (modules.pagination) {
				tableData.lastPage = Math.ceil((tableData.total - 1) / tableData.size)
			}
			ElNotification({ type: "success", message: "操作成功!" })
			reload()
		} catch (error) {
			ElNotification({ type: "error", message: error })
		}
	}
	async function toExport(tableOptions) {
		const headerList = tableOptions
			.filter(item => item.key && item.show)
			.map(item => ({
				name: item.title,
				code: item.key,
			}))
		try {
			await postAxios(
				modules.exportUrl,
				{
					dot: search,
					headerList,
				},
				{
					responseType: "blob",
					download: {
						filename: `${formatDate(new Date(), "YYYY年MM月DD日hh时mm分ss秒")}-导出文件.xlsx`,
						type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
					},
				}
			)
		} catch (error) {
			ElNotification({ type: "error", message: error })
		}
	}
	function toBatchDelete(select) {
		ElMessageBox.confirm("确定要删除这些数据吗?", "提示", {
			type: "error",
		})
			.then(async () => {
				let ids = []
				if (Array.isArray(select)) {
					ids = select.map(item => item.id)
				} else if (typeof select === "string" || typeof select === "number") {
					ids = [select]
				} else {
					ids = selection.value.map(item => item.id)
				}
				try {
					await postAxios(modules.batchDeleteUrl, {
						ids,
					})
					ElNotification({ type: "success", message: "操作成功!" })
					reload()
				} catch (error) {
					ElNotification({ type: "error", message: error })
				}
			})
			.catch(() => {})
	}
	onActivated(reload)
	return {
		...basis,
		loading,
		tableLoading,
		search,
		selection,
		tableData,
		reload,
		toSearch,
		toRefreshSearch,
		onSizeChange,
		onCurrentChange,
		toDelete,
		toExport,
		toBatchDelete,
	}
}
